import React, { useState, useEffect } from 'react';
import { useKeycloak } from '@react-keycloak/web';
import axios from 'axios';

function ProductList() {
  const { keycloak, initialized } = useKeycloak();
  const [products, setProducts] = useState(null);

  useEffect(() => {
    if (keycloak.authenticated) {
      axios.get('http://localhost:8088/products', {
        headers: {
          Authorization: `Bearer ${keycloak.token}`,
        }
      })
      .then(response => {
        setProducts(response.data);
      })
      .catch(error => {
        console.error("Failed to fetch products", error);
      });
    }
  }, [keycloak, keycloak.authenticated]);

  if (!initialized || !keycloak.authenticated) {
    return <div>Loading...</div>;
  }

  if (!products) {
    return <div>Fetching products...</div>;
  }

  return (
    <div>
      <h2>Product List</h2>
      <ul>
        {products.map((product, index) => (
          <li key={index}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default ProductList;
